﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using ServerLibForClient;
using System.IO;
using ClientLib;

namespace ServerConsole
{
    public class Agent
    {
        //! lifeTimeService

        Server curentServer;
        public Server CurentServer
        {
            get { return curentServer; }
            set { curentServer = value; }
        }

        SearchRequestStruct searchRequestData;
        public SearchRequestStruct SearchRequestData
        {
            get { return searchRequestData; }
        }

        Thread workThread;

        Finder finder;

        /// <summary> Флаг окончания поиска </summary>
        bool isFindFinish = false;
        /// <summary> Флаг получения сообщения о размножении </summary>
        bool isProliferationRequestReceived = false;

        public Agent(SearchRequestStruct searchRequestData, Server curentServer)
        {
            this.searchRequestData = searchRequestData;
            this.curentServer = curentServer;
            workThread = new Thread(doWork);
            curentServer.SearchRequestEvent += new Server.ReciveCommantGetSerchAgentsEventHandler(curentServer_SearchRequestEvent);
        }

        void curentServer_SearchRequestEvent(string host, string port, string searchRequestHash)
        {
            // получили запрос на агента
        }

        ~Agent()
        {
            if (workThread != null)
                workThread.Abort();
        }

        public void Start()
        {
            if (workThread.IsAlive)
            {
                throw new Exception("Аген уже запущен");
            }

            workThread.Start();
        }

        void doWork()
        {
            BeginFind(); // Выполнение асинхронного поиска
            BeginProliferation(); // Размножение
            BeginMigration(); // Миграция
        }

        void BeginFind()
        {
            // Выполнение асинхронного посика
            finder = new Finder();
            finder.BeginFind(searchRequestData.SerchData, curentServer.baseFolger, SearchOption.TopDirectoryOnly, FindResult);
        }

        void BeginProliferation()
        {
            //! Выполнение размножения
            while (!isFindFinish)
            {
                if (isProliferationRequestReceived)
                {
                    isProliferationRequestReceived = false;
                    Thread.Sleep(500);
                }
                else
                {

                }
            }
        }

        void BeginMigration()
        {
            curentServer.GetFreeHosts(searchRequestData.Sha1Hash);
            Thread.Sleep(5000);
            lock (curentServer.FreeHost)
            {
                if (curentServer.FreeHost != string.Empty)
                {
                    SearchRequest SearchRequestProxy = (SearchRequest)Activator.GetObject(typeof(SearchRequest), "tcp://" + curentServer.FreeHost + "/SearchRequest.soap");
                    SearchRequestProxy.BeginSerch(searchRequestData);
                }
            }
        }

        void FindResult(string findData, bool isCompleted)
        {
            try
            {
                // Соединение с клиентом и отправка результата.
                if (!isCompleted)
                {
                    ResultFunctions ResultFunctionsProxy = (ResultFunctions)Activator.GetObject(typeof(ResultFunctions), searchRequestData.ClientHost + ":" + searchRequestData.Port + "/ResultFunctions.soap");
                    ResultStruct res = new ResultStruct(findData, curentServer.HostName);

                    ResultFunctionsProxy.ReturnResult(res);
                }
                else
                {
                    isFindFinish = true;
                }
            }
            catch (System.Exception ex)
            {
            }
        }
    }
}
